layui.use(['table', 'admin', 'ax','laydate','form'], function () {
    var $ = layui.$;
    var table = layui.table;
    var $ax = layui.ax;
    var admin = layui.admin;
    var form = layui.form;
    var laydate = layui.laydate;

    laydate.render({
      elem: '#startTime'
        	,value:new Date()
    });

    laydate.render({
      elem: '#endTime'
        	,value:new Date()
    });

    /**
     * 调度单表管理
     */
    var TDispatch = {
        tableId: "tDispatchTable"
    };
    
    /**
     * 初始化表格的列
     */
    TDispatch.initColumn = function () {
        return [[
            {type: 'checkbox'},
            {field: 'operateName', title: '项目', style:'font-weight: 600;'},
            {field: 'trainNumber', title: '车次', style:'font-weight: 600;', sort: true},
            {field: 'startDate', title: '发车日期', style:'font-weight: 600;', sort: true},
            {field: 'dispatchNumber', title: '运输单号', style:'font-weight: 600;',templet: '#dispatchNumberTpl'},
            {field: 'customerOrder', title: '客户单号', style:'font-weight: 600;'},
            {field: 'carnumber', title: '车牌号', style:'font-weight: 600;', style:'background-color: #dbf1e1;font-weight: 600;',width:150},
            {field: 'siji', title: '司机', style:'font-weight: 600;', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'sijidianhua', title: '联系方式', style:'font-weight: 600;', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'chexing', title: '车型', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'mileageTraveled', title: '行驶里程', style:'background-color: #dbf1e1;font-weight: 600;', sort: true},
            {field: 'loadingType', title: '装车方', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'loadingPersonnel', title: '装车人员', style:'background-color: #dbf1e1;font-weight: 600;'},
            {field: 'zhunzailiang', title: '准载方数m3', style:'background-color: #dbf1e1;font-weight: 600;', sort: true},
            {field: 'fulllv', title: '满载率%', style:'font-weight: 600;', style:'background-color: #dbf1e1;font-weight: 600;', totalRowText: '合计：', sort: true},
            {field: 'getUnits', title: '收货客户', style:'font-weight: 600;',width:180},
            {field: 'toovolume', title: '总方数m3', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'tooNum', title: '总数量', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'toomoney', title: '货值', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'matrixingNumber', title: '换算合计', style:'font-weight: 600;', totalRow: true, sort: true},
            {field: 'chengyunfangshi', title: '承运方式', style:'font-weight: 600;'},
            {field: 'chengyunleixing', title: '承运类型', style:'font-weight: 600;'},
            {field: 'carrierName', title: '承运商', style:'font-weight: 600;'},
            {field: 'lineName', title: '线路', style:'font-weight: 600;'},
            {field: 'money', sort: true, title: '付款金额', style:'font-weight: 600;', totalRow: true},
            {field: 'freightMoney', sort: true, title: '运费', style:'font-weight: 600;', totalRow: true},
            {field: 'consultMoney', title: '参考运费￥', style:'font-weight: 600;',templet: '#consultMoneyTpl', totalRow: true},
            {field: 'loadingMoney', sort: true, title: '装车费', style:'font-weight: 600;', totalRow: true},
            {field: 'xiechefei', sort: true, title: '卸车费', style:'font-weight: 600;', totalRow: true},
            {field: 'stateTb', title: '提报状态', style:'font-weight: 600;', totalRow: true},
            {field: 'stateTbTime', title: '提报时间', style:'font-weight: 600;', totalRow: true},
        ]];
    };


    /**
     * 导出excel按钮
     */
    TDispatch.exportExcel = function () {
        var checkRows = table.checkStatus(TDispatch.tableId);
        var originalColumns = TDispatch.initColumn()[0];
        var dataToExport = checkRows.data;

        if (checkRows.data.length === 0) {
            Feng.error("请选择要导出的数据");
        } else {
            // 移除不需要的数据字段
            dataToExport = dataToExport.map(function (row) {
                delete row.id;
                delete row.center;
                row.dispatchNumber = row.dispatchNumber.trim();
                return row;
            });

            // 创建新的 columns 数组，只包含需要导出的列
            originalColumns = originalColumns.filter(column => {
                // 排除表头
                return column.field !== 'id' && column.field !== 'center';
            });

            layer.confirm('请选择要导出格式：', {
                btn: ['xlsx', 'xls'],
                skin: 'layui-layer-molv'
            }, function (index) {
                // exportToXlsx(dataToExport, originalColumns, '承运商装运统计.xlsx');
                tableToExcel(dataToExport, originalColumns, '承运商装运客户统计.xlsx');
                layer.close(index);
            }, function (index) {
                table.exportFile(tableResult.config.id, checkRows.data, 'xls')
                layer.close(index);
            })
        }
    };

    // 导出excel
    $('#btnExp').click(function () {
        TDispatch.exportExcel();
    });

    /**
     * 点击查询按钮
     */
    TDispatch.search = function () {
        var queryData = {};
        queryData['driver1'] = $("#driver1").val();
        queryData['carnumber'] = $("#carnumber").val();
        queryData['chexing'] = $("#chexing").val();
        queryData['getUnit'] = $("#getUnit").val();
        queryData['condition'] = $("#condition").val();
        queryData['startTime'] = $("#startTime").val();
        queryData['endTime'] = $("#endTime").val();
        queryData['operateId'] = $("#operateId").val();
        queryData['operateName'] = $("#operateName").val();
        queryData['carrierId'] = $("#carrierId").val();
        queryData['carrierName'] = $("#carrierName").val();
        table.reload(TDispatch.tableId, {
            where: queryData, page: {curr: 1},
			done: function (res, curr, count) {
			}
        });
    };

    // 渲染表格
    var tableResult = table.render({
        elem: '#' + TDispatch.tableId,
        url: Feng.ctxPath + '/tDispatch/findchengyunshangcount',
        page: false,
        limit: 1000,
        height: "full-60",
        totalRow: true,
        toolbar: '#toolbarDemo', //开启头部工具栏，并为其绑定左侧模板
        defaultToolbar: ['filter', 'exports', 'print'],
        cellMinWidth: 100,
        cols: TDispatch.initColumn(),
    });

    // 搜索按钮点击事件
    $('#btnSearch').click(function () {
        TDispatch.search();
    });

    // 单击行事件
    table.on('row(' + TDispatch.tableId + ')', function (obj) {
        var data = obj.data;
		$('div[lay-id="' + TDispatch.tableId + '"]').find(".layui-table-body tr ").attr({ "style": "background:#FFFFFF" });//其他tr恢复原样
		$('div[lay-id="' + TDispatch.tableId + '"]').find(obj.tr.selector).attr({ "style": "background:#e6e6e6" });//改变当前tr颜色
    });

    // 工具条点击事件
    table.on('tool(' + TDispatch.tableId + ')', function (obj) {
        var data = obj.data;
        var layEvent = obj.event;

        if (layEvent === 'tooDetailed') {
            layer.open({
                type: 2,
                title: '配送派车信息',
                area: ['1250px', '570px'],
                anim: 5,
                content: Feng.ctxPath + '/tDispatch/tooDetailed?dispatchNumber=' + data.dispatchNumber,
            });
        } else if (layEvent === 'tooConsultMoneyDetailed') {
            layer.open({
                type: 2,
                title: '费用信息',
                area: ['1100px', '500px'],
                anim: 5,
                content: Feng.ctxPath + '/transportCost?dispatchNumber=' + data.dispatchNumber,
            });
        }
    });

    //查询库区
    form.on('select(operateId)',function(){
        $("#carrierId").empty();
        $.ajax({
            url:Feng.ctxPath + '/basicCarrier/Querylist',
            dataType:"json",   //返回格式为json
            async: false,
            data:{"operateId":$("#operateId").val()},    //参数值
            type:"post",   //请求方式
            success:function(data){
                if(data.length>0){
                    var str = "<option value=''>选择承运商</option>";
                    $.each(data,function(key,value){
                        str += "<option value='"+value.id+"'>"+value.carrierName+"</option>";
                    });
                    $("#carrierId").html(str);
                }
            }
        });
        form.render('select');
    });
    
});
